from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
import base64

# 生成RSA密钥对
def generate_key_pair():
    key = RSA.generate(2048)
    private_key = key.export_key()
    public_key = key.publickey().export_key()
    return private_key, public_key

# RSA加密
def rsa_encrypt(public_key, data):
    recipient_key = RSA.import_key(public_key)
    cipher_rsa = PKCS1_OAEP.new(recipient_key)
    encrypted_data = cipher_rsa.encrypt(data)
    return encrypted_data

# RSA解密
def rsa_decrypt(private_key, data):
    private_key = RSA.import_key(private_key)
    cipher_rsa = PKCS1_OAEP.new(private_key)
    decrypted_data = cipher_rsa.decrypt(data)
    return decrypted_data

private_key,public_key = generate_key_pair()
data = b"Hello, World! This is RSA test msg"
encrypt_data = rsa_encrypt(public_key,data)
decrypt_data = rsa_decrypt(private_key,encrypt_data)

print("加密数据: ",encrypt_data)
print("解密数据: ",decrypt_data)
print("数据是否一致:", data == decrypt_data)